package cn.xiaopengstack.infrastructure.event;

import cn.xiaopengstack.types.event.BaseEvent;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class EventPublisher {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void publish(BaseEvent<?> event) {
        BaseEvent.EventMessage<?> payload = event.payload();
        String topic = event.topic();
        try {
            rocketMQTemplate.convertAndSend(topic, payload);
            log.info("发送MQ消息失败 topic:{}, message:{}", topic, JSONObject.toJSONString(payload));
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic:{}, message:{}", topic, JSONObject.toJSONString(payload), e);
            throw e;
        }
    }

}
